<!-- 收费分类管理 -->
<template>
	<el-breadcrumb separator="/">
		<el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
		<el-breadcrumb-item :to="{ path: '/counselorInfo' }">咨询师信息管理</el-breadcrumb-item>
		<el-breadcrumb-item>收费分类管理</el-breadcrumb-item>
	</el-breadcrumb>

	<el-form :inline="true" :model="queryInfo" class="demo-form-inline">
		<el-form-item label="收费分类">
			<el-input v-model="queryInfo.sortName" placeholder="请输入收费分类" clearable />
		</el-form-item>
		<el-form-item>
			<el-button type="primary" @click="queryDataList">搜索</el-button>
			<el-button type="primary" @click="add">新增收费分类</el-button>
			<el-button type="danger" @click="batchRemove">批量删除</el-button>
		</el-form-item>
	</el-form>

	<el-dialog :title="title" v-model="dialogFormVisible" width="950" @close="cancle">
		<el-form :model="chargeSortData" label-width="100px">
			<el-form-item label="收费分类">
				<el-input v-model="chargeSortData.sortName" autocomplete="off" placeholder="请输入收费分类"></el-input>
			</el-form-item>
		</el-form>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="cancle">取消</el-button>
				<el-button type="primary" @click="confirm">确定</el-button>
			</div>
		</template>
	</el-dialog>

	<el-table :data="dataList" row-key="id" style="width: 100%" @selection-change="handleSelectionChange">
		<el-table-column fixed="left" type="selection" width="55" />
		<el-table-column fixed="left" property="id" label="ID" width="60" />
		<el-table-column property="classify" label="收费分类" />
		<el-table-column fixed="right" label="操作" min-width="120">
			<template #default="scope">
				<el-button type="primary" size="small" @click="edit(scope.row)">编辑</el-button>
				<el-button type="danger" size="small" @click="remove(scope.row.id)" v-if="scope.row.id">删除</el-button>
			</template>
		</el-table-column>
	</el-table>

	<el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5,10,15,20]"
		:size="size" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
		@current-change="handleCurrentChange" />

	<router-view></router-view>
</template>

<script lang="ts" setup>
	import { getCurrentInstance, onMounted, reactive, ref } from 'vue'
	import { ElMessage, ElMessageBox } from 'element-plus'

	const { appContext } = getCurrentInstance()!
	const axios = appContext.config.globalProperties.axios

	const pageSize = ref(5)
	const currentPage = ref(1)
	const size = ref('default')

	const queryInfo = reactive({
		sortName: '',
		pageNum: 1,
		pageSize: 5
	})

	const total = ref(0)
	const dataList = ref<any[]>([])
	const multipleSelection = ref<number[]>([])

	const title = ref('')
	const dialogFormVisible = ref(false)
	const chargeSortData = ref({
		sortName: '',
		id: '',
		del: 0
	})

	const queryDataList = () => {
		axios.get("/chargeSort/page", { params: queryInfo })
			.then(res => {
				if (!res || !Array.isArray(res.list)) {
					dataList.value = []
					total.value = 0
					ElMessage.error("数据加载失败")
					return
				}

				dataList.value = res.list.map(item => ({
					id: item.id,
					classify: item.sortName,
					del: item.del ?? 0
				}))
				total.value = res.total || 0
			})
			.catch(error => {
				ElMessage.error("查询失败")
			})
	}

	onMounted(() => {
		queryDataList()
	})

	const handleSelectionChange = (val : any[]) => {
		multipleSelection.value = val.map(item => item.id)
	}

	const handleSizeChange = (val : number) => {
		queryInfo.pageSize = val
		queryDataList()
	}

	const handleCurrentChange = (val : number) => {
		queryInfo.pageNum = val
		queryDataList()
	}

	const cancle = () => {
		chargeSortData.value = { sortName: '', id: '', del: 0 }
		dialogFormVisible.value = false
	}

	const confirm = () => {
		if (!chargeSortData.value.sortName.trim()) {
			ElMessage.warning("请输入收费分类名称")
			return
		}

		if (chargeSortData.value.id) {
			axios.put(`/chargeSort/${chargeSortData.value.id}`, chargeSortData.value)
				.then(resp => {
					if (resp.includes('成功')) {
						ElMessage.success("修改成功")
						dialogFormVisible.value = false
						queryDataList()
					} else {
						ElMessage.error("修改失败: " + resp)
					}
				})
				.catch(() => {
					ElMessage.error("修改请求失败")
				})
		} else {
			const newData = { ...chargeSortData.value, del: 0 }
			axios.post('/chargeSort', newData)
				.then(resp => {
					if (resp.includes('成功')) {
						ElMessage.success("新增成功")
						dialogFormVisible.value = false
						queryInfo.sortName = ''
						queryDataList()
					} else {
						ElMessage.error("新增失败: " + resp)
					}
				})
				.catch(() => {
					ElMessage.error("新增请求失败")
				})
		}
	}

	const add = () => {
		title.value = '新增收费分类'
		chargeSortData.value = { sortName: '', id: '', del: 0 }
		dialogFormVisible.value = true
	}

	const edit = (row : any) => {
		title.value = '编辑收费分类'
		chargeSortData.value = {
			sortName: row.classify,
			id: row.id,
			del: row.del ?? 0
		}
		dialogFormVisible.value = true
	}

	// 单个删除
	const remove = (id: number) => {
	  if (!id) {
	    ElMessage.warning("无效的删除目标");
	    return;
	  }
	
	  ElMessageBox.confirm('此操作将永久删除该收费分类, 是否继续?', '警告', {
	    confirmButtonText: '确定',
	    cancelButtonText: '取消',
	    type: 'warning',
	  }).then(() => {
	    axios.delete(`/chargeSort/${id}`)
	      .then(resp => {
	        // 成功处理（保持不变）
	        if (resp.includes('成功')) {
	          ElMessage.success('删除成功');
	          queryDataList();
	        } else {
	          ElMessage.error('删除失败: ' + resp.data);
	        }
	      })
	      // 新增：捕获后端抛出的异常（如关联收费标准时）
	      .catch(error => {
	        // 提取后端异常消息（根据实际响应结构调整）
	        const errorMsg = error.response?.data?.message || error.message || '删除失败，请检查该分类下是否存在收费标准';
	        ElMessage.error(errorMsg);
	      });
	  }).catch(() => {
	    // 取消删除的提示（保持不变）
	    ElMessage({ type: 'info', message: '已取消删除' });
	  });
	};
	
	// 批量删除
	const batchRemove = () => {
	  if (multipleSelection.value.length === 0) {
	    ElMessage.warning('请选择要删除的收费分类');
	    return;
	  }
	
	  ElMessageBox.confirm('此操作将永久删除选中收费分类, 是否继续?', '警告', {
	    confirmButtonText: '确定',
	    cancelButtonText: '取消',
	    type: 'warning',
	  }).then(() => {
	    axios.delete('/chargeSort', {
	      params: { ids: multipleSelection.value.join(',') }
	    }).then(resp => {
	      // 成功处理（保持不变）
	      if (resp.includes('成功')) {
	        ElMessage.success('批量删除成功');
	        queryDataList();
	        multipleSelection.value = [];
	      } else {
	        ElMessage.error('批量删除失败: ' + resp.data);
	      }
	    })
	    // 新增：捕获后端抛出的异常（如关联收费标准时）
	    .catch(error => {
	      const errorMsg = error.response?.data?.message || error.message || '批量删除失败，请检查选中分类下是否存在收费标准';
	      ElMessage.error(errorMsg);
	    });
	  }).catch(() => {
	    // 取消删除的提示（保持不变）
	    ElMessage({ type: 'info', message: '已取消删除' });
	  });
	};
</script>

<style scoped>
	.el-breadcrumb {
		margin-bottom: 15px;
		padding-bottom: 15px;
		border-bottom: 1px solid #eee;
	}

	.el-pagination {
		margin-top: 15px;
		text-align: right;
	}

	
</style>